//
//  WebViewControllerCJT.m
//  BreadTravel
//
//  Created by dllo on 15/12/23.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "WebViewControllerCJT.h"
#import "CoreDataModel.h"
#import "CoreDataManager.h"

@interface WebViewControllerCJT ()

@property(nonatomic, assign)BOOL isSelected;
@property(nonatomic, retain)NSManagedObjectContext *managedObjectContext;
@property(nonatomic, strong)UIButton *btn;

@end

@implementation WebViewControllerCJT


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIImage *leftImage = [UIImage imageNamed:@"btn_nav_back@2x.png"];
    leftImage = [leftImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:leftImage style:UIBarButtonItemStyleDone target:self action:@selector(leftButtonAction:)];
    
    _managedObjectContext = [[CoreDataManager shareManager] managedObjectContext];
    //打印沙盒路径
    NSLog(@"沙盒路径~~~~~~ %@", [[CoreDataManager shareManager] applicationDocumentsDirectory]);
    
    
    NSString *url = [NSString stringWithFormat:@"%@", self.webURL];
    
    NSURL *urlStr = [NSURL URLWithString:url];
    
    //UIWebView
    UIWebView *webView = [[UIWebView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    
    
    NSURLRequest *request = [NSURLRequest requestWithURL:urlStr];
    [self.view addSubview:webView];
    [webView loadRequest:request];
    
    
    self.btn = [UIButton buttonWithType:UIButtonTypeCustom];
    /**
     *  设置frame只能控制按钮的大小
     */
    self.btn.frame= CGRectMake(0, 0, 30, 30);
    [self.btn addTarget:self action:@selector(rightAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 设置背景图片
    [self.btn setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucangjia.png"] forState:UIControlStateNormal];
    // 设置选中状态时的背景图片
    [self.btn setBackgroundImage:[UIImage imageNamed:@"iconfont-yijingshoucang.png"] forState:UIControlStateSelected];
    
    
    UIBarButtonItem *btn_right = [[UIBarButtonItem alloc] initWithCustomView:self.btn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    
    

    
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_right, nil];

    
    
    [self panDuanShiFouYiBeiShouCang];
}
//返回
-(void)leftButtonAction:(UIBarButtonItem *)bar{
    
    [self.navigationController popToRootViewControllerAnimated:NO];
    
}
-(void)panDuanShiFouYiBeiShouCang
{

    //取
    //查询请求
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    //获取要查询的实体的描述
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"CoreDataModel" inManagedObjectContext:_managedObjectContext];
    //对fetchRequest设置查询的实体
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    //谓词
    //        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@", @"马强"];
    //        [fetchRequest setPredicate:predicate];
    //     Specify how the fetched objects should be sorted
    //排序
    //第一个参数：按哪个字段排序
    //第二个参数：是否升序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"titleName"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    //从数据库中搜索满足上述条件的元素
    
    NSArray *fetchedObjects = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"error : %@", error);
    }
    
    NSMutableArray *array= [NSMutableArray array];
    NSMutableArray *arr = [NSMutableArray arrayWithArray:fetchedObjects];
    
    for (CoreDataModel *model in arr) {
        [array addObject:model.titleName];
        
    }

    if ([array containsObject:self.titleName]) {
        
        self.btn.selected = YES;
        
    }else{
    
        self.btn.selected = NO;
        
    }
}




-(void)rightAction:(UIButton *)btn
{
    
    btn.selected = !btn.selected;
    //关键帧动画
    CAKeyframeAnimation *keyAnimtion = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    keyAnimtion.values = @[@(0.1),@(1.0),@(1.5)];
    
    keyAnimtion.duration = 0.2;
    [btn.layer addAnimation:keyAnimtion forKey:@"key"];
    
    if (self.isSelected == NO) {
        [btn setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucangjia.png"] forState:(UIControlStateNormal)];
    }else{
        [btn setBackgroundImage:[UIImage imageNamed:@"iconfont-yijingshoucang.png"] forState:(UIControlStateNormal)];
        
    }

    
    //取
    //查询请求
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    //获取要查询的实体的描述
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"CoreDataModel" inManagedObjectContext:_managedObjectContext];
    //对fetchRequest设置查询的实体
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    //谓词
//        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@", @"马强"];
//        [fetchRequest setPredicate:predicate];
//     Specify how the fetched objects should be sorted
    //排序
    //第一个参数：按哪个字段排序
    //第二个参数：是否升序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"titleName"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    //从数据库中搜索满足上述条件的元素
    
    NSArray *fetchedObjects = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"error : %@", error);
    }
    
    NSMutableArray *array= [NSMutableArray array];
    NSMutableArray *arr = [NSMutableArray arrayWithArray:fetchedObjects];
    
    for (CoreDataModel *model in arr) {
        [array addObject:model.titleName];
        NSLog(@"上-----  %@", model.titleName);
    }
    NSLog(@"上   %@", self.titleName);
    
    
   

    
    if ([array containsObject:self.titleName]) {
        
        
        NSInteger index = [array indexOfObject:self.titleName];
        NSLog(@"//////// %lu", index);
        
        CoreDataModel *model = arr[index];
        [_managedObjectContext deleteObject:model];
        [[CoreDataManager shareManager] saveContext];
        
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        //显示的文字
        hud.labelText = @"取消收藏";
        //是否有遮罩
        hud.dimBackground = NO;
        hud.labelFont = [UIFont boldSystemFontOfSize:22];
        hud.backgroundColor = [UIColor clearColor];
        //提示框的样式
        hud.mode = MBProgressHUDModeCustomView;
        [hud show:YES];
        //两秒之后隐藏
        [hud hide:YES afterDelay:2];

        
    }else{
        
        CoreDataModel *model = [NSEntityDescription insertNewObjectForEntityForName:@"CoreDataModel" inManagedObjectContext:_managedObjectContext];
        
        model.titleName = self.titleName;
        model.imageName = self.imageName;
        model.webURL = self.webURL;
        [[CoreDataManager shareManager] saveContext];
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        //显示的文字
        hud.labelText = @"收藏成功";
        //是否有遮罩
        hud.dimBackground = NO;
        hud.labelFont = [UIFont boldSystemFontOfSize:22];
        hud.backgroundColor = [UIColor clearColor];
        //提示框的样式
        hud.mode = MBProgressHUDModeCustomView;
        [hud show:YES];
        //两秒之后隐藏
        [hud hide:YES afterDelay:2];
    

        
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
